import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../models/field_info.dart';
import '../../app/modules/project/interface/controllers/interface_controller.dart';

class JsonItem extends StatelessWidget {
  final FieldInfo field;
  final int depth;

  JsonItem({super.key, required this.field, this.depth = 0});
  final InterfaceController controller = Get.find();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              // 字段名
              Container(
                width: Get.width * 0.4,
                padding: EdgeInsets.only(left: depth * 20),
                child: TextField(
                  controller: TextEditingController(text: field.name),
                  decoration: InputDecoration(
                    labelText: '字段名',
                    isDense: true,
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 8,
                    ),
                  ),
                  onChanged: (value) =>
                      controller.updateFieldName(field.id, value),
                ),
              ),

              SizedBox(width: 8),

              // 字段类型
              Expanded(flex: 1, child: _TypeDropdown(field: field)),
              SizedBox(width: 8),

              // 字段备注
              Expanded(
                flex: 2,
                child: TextField(
                  controller: TextEditingController(
                    text: field.description ?? '',
                  ),
                  decoration: InputDecoration(
                    labelText: '备注',
                    isDense: true,
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 8,
                    ),
                  ),
                  onChanged: (value) =>
                      controller.updateFieldDescription(field.id, value),
                ),
              ),
              SizedBox(width: 8),

              // 操作按钮
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 添加按钮 - 仅对对象和数组类型显示
                  if (field.type == FieldType.object ||
                      field.type == FieldType.array)
                    IconButton(
                      icon: Icon(Icons.add, size: 20),
                      onPressed: () => _showAddFieldDialog(context, field.id),
                      tooltip: '添加子字段',
                    ),

                  // 删除按钮 - 根字段不显示删除按钮
                  IconButton(
                    icon: Icon(Icons.delete, size: 20, color: Colors.red),
                    onPressed: () => controller.removeField(field.id),
                    tooltip: '删除字段',
                  ),
                ],
              ),
            ],
          ),

          // 第三行：子字段（仅对对象和数组类型显示）
          if ((field.type == FieldType.object ||
                  field.type == FieldType.array) &&
              field.children != null &&
              field.children!.isNotEmpty)
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 8),
                Text(
                  field.type == FieldType.object ? '对象属性:' : '数组元素:',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                ...field.children!.map(
                  (child) => JsonItem(field: child, depth: depth + 1),
                ),
              ],
            ),

          // 空状态提示
          if ((field.type == FieldType.object ||
                  field.type == FieldType.array) &&
              (field.children == null || field.children!.isEmpty))
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Text(
                '暂无${field.type == FieldType.object ? '属性' : '元素'}',
                style: TextStyle(
                  color: Colors.grey,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
        ],
      ),
    );
  }

  void _showAddFieldDialog(BuildContext context, String parentId) {
    final InterfaceController controller = Get.find();
    final nameController = TextEditingController();
    final descriptionController = TextEditingController();
    FieldType selectedType = FieldType.string;

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('添加新字段'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: InputDecoration(labelText: '字段名'),
              ),
              SizedBox(height: 16),
              DropdownButtonFormField<FieldType>(
                value: selectedType,
                items: FieldType.values.map((type) {
                  return DropdownMenuItem(
                    value: type,
                    child: Text(_getTypeString(type)),
                  );
                }).toList(),
                onChanged: (FieldType? newValue) {
                  if (newValue != null) {
                    selectedType = newValue;
                  }
                },
                decoration: InputDecoration(labelText: '字段类型'),
              ),
              SizedBox(height: 16),
              TextField(
                controller: descriptionController,
                decoration: InputDecoration(labelText: '字段备注'),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                final newField = FieldInfo(
                  name: nameController.text,
                  type: selectedType,
                  description: descriptionController.text.isNotEmpty
                      ? descriptionController.text
                      : null,
                );
                controller.addField(parentId, newField);
                Navigator.of(context).pop();
              },
              child: Text('添加'),
            ),
          ],
        );
      },
    );
  }

  String _getTypeString(FieldType type) {
    switch (type) {
      case FieldType.string:
        return '字符串';
      case FieldType.number:
        return '数字';
      case FieldType.boolean:
        return '布尔值';
      case FieldType.object:
        return '对象';
      case FieldType.array:
        return '数组';
      case FieldType.nullType:
        return '空值';
      default:
        return '未知';
    }
  }
}

class _TypeDropdown extends StatelessWidget {
  final FieldInfo field;

  const _TypeDropdown({Key? key, required this.field}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final InterfaceController controller = Get.find();

    return DropdownButton<FieldType>(
      value: field.type,
      items: FieldType.values.map((FieldType type) {
        return DropdownMenuItem<FieldType>(
          value: type,
          child: Chip(
            label: Text(
              _getTypeString(type),
              style: TextStyle(fontSize: 12, color: Colors.white),
            ),
            backgroundColor: _getTypeColor(type),
          ),
        );
      }).toList(),
      onChanged: (FieldType? newValue) {
        if (newValue != null) {
          controller.updateFieldType(field.id, newValue);
        }
      },
    );
  }

  String _getTypeString(FieldType type) {
    switch (type) {
      case FieldType.string:
        return 'String';
      case FieldType.number:
        return 'Number';
      case FieldType.boolean:
        return 'Boolean';
      case FieldType.object:
        return 'Object';
      case FieldType.array:
        return 'Array';
      case FieldType.nullType:
        return 'Null';
      default:
        return 'Unknown';
    }
  }

  Color _getTypeColor(FieldType type) {
    switch (type) {
      case FieldType.string:
        return Colors.blue;
      case FieldType.number:
        return Colors.green;
      case FieldType.boolean:
        return Colors.orange;
      case FieldType.object:
        return Colors.purple;
      case FieldType.array:
        return Colors.red;
      case FieldType.nullType:
        return Colors.grey;
      default:
        return Colors.black;
    }
  }
}
